<template>
  <div>
    <section class="shortcut w">
      <div>
        <div class="fl">
          <ul>
            <li class="Logo"><router-link
              :to="{path: '/', name: 'user'}"
            >书城Logo</router-link></li>
            <li><router-link
              :to="{path: '/shoppingCar', name: 'userShopCar'}"
            >我的购物车</router-link> &nbsp; </li>
            <li><router-link
              :to="{path: '/booksOrder', name: 'userBookOrder'}"
            >订单管理</router-link> &nbsp; </li>
          </ul>
        </div>
      </div>
    </section>
    <div class="w">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%; marginTop: 40px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="全选"
          width="60"
          :style="{marginLeft: '-50px',fontWeight: 'bold',color: '#000'}"
        />
        <el-table-column
          label="图片"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <div style="width: 140px; height: 140px; ">
              <img
                :src="scope.row.book.cover"
                :style="{width: '140px', height: '140px'}"
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="book.bookName"
          label="商品名称"
          width="200"
          align="center"
        />
        <el-table-column
          label="数量"
          width="200"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.num" size="small" :min="1" :max="100" @change="handleChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          prop="book.price"
          label="单价/￥"
          width="200"
          align="center"
          fixed="right"
        />
        <el-table-column
          prop="total"
          label="总价/￥"
          width="200"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <span style="color: #000;font-weight: bold">{{ scope.row.total }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-button type="danger" @click="toggleSelection(), clickHandler($event)">批量删除</el-button>
        <div class="fr" style="font-size: 20px; color: red ; font-weight: bold">总计： ￥{{ totalCost }}</div>
      </div>
      <el-divider />
      <div class="footer">
        <div>
          <span
            class="fl clearfix"
            :style="{
              display: 'block',
              height: '40px',
              width: '5%',
              backgroundColor: '#eee',
              lineHeight: '40px',
              textAlign: 'center',
              fontSize: '14px',
              color: '#333',
              border: '1px solid #eee',
              borderRadius: '4px 0 0 4px'
            }"
          >收货地址</span>
          <el-input v-model="input" class="fr" placeholder="留空即做默认地址处理" style="width: 95%" />
        </div>
        <el-button type="success" class="fr" :plain="true" style="margin: 30px 20px" @click="addOrder(), clickHandler($event)">生成订单</el-button>
        <div
          :style="{
            float: 'right',
            height: '40px',
            width: '100%',
            backgroundColor: '#eee',
            lineHeight: '40px',
            paddingLeft: '20px',
            fontSize: '12px',
            color: '#333',
            border: '1px solid #eee',
            borderRadius: '4px 0 0 4px'
          }"
        >
          <span style="font-weight: bold">注意：</span>请在30日内完成付款，否则订单取消。
        </div>
      </div>
      <div style="float:left; margin-top: 100px; height: 1px; width: 1px" />
    </div>
  </div>

</template>

<script>
import userApi from '@/api/user'

export default {
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      input: '',
      user: false,
      userId: 0
    }
  },
  computed: {
    totalCost: function() {
      let cost = 0.0
      // 统计勾选项的总金额
      if (this.multipleSelection) {
        this.multipleSelection.forEach(checked => {
          cost += checked.total
        })
        return cost
      } else return 0.0
    }

  },

  created: function() {
    this.userId = window.sessionStorage.getItem('token')
    userApi.getAllCart(this.userId).then(resp => {
      this.tableData = [] // 清空原有数据
      var booksInfo = [] // 存放购物车中的图书id以及数目
      var IDs = resp.data.data[this.userId]
      IDs.forEach(Info => {
        booksInfo.push({ id: Info.bookId, num: Info.bookNumber }) // 存入购物车中每本书的id以及数目
      })
      booksInfo.forEach(book => {
        userApi.getBookById(book.id).then(resp => {
          this.tableData.push({ book: resp.data.data[book.id], num: book.num, total: resp.data.data[book.id].price * book.num }) // 根据id将图书信息存入tableData
        })
      })
    }, err => {
      console.log(err)
    })
  },

  methods: {
    // 勾选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 金额实时变化
    handleChange(item) {
      this.num = item.num
      item.total = item.book.price * item.num
      userApi.cartUpdateNumber(this.userId,
        { 'bookId': item.book.id,
          'bookNumber': item.num
        }
      ).then(resp => {

      }, err => {
        console.log(err)
      })
    },
    addOrder() {
      var order = []
      this.multipleSelection.forEach(data => {
        order.push({ bookId: data.book.id, bookNumber: data.num })
      })
      userApi.createOrder(this.userId, order).then(resp => {
        this.$message({
          message: '下单成功！',
          type: 'success',
          duration: 2000
        })
      }, err => {
        this.$message({
          message: '订单生成异常！',
          type: 'error',
          duration: 2000
        })
        console.log(err)
      })
    }
  }

}
</script>

<style scoped>
.el-table .cell {
    overflow: visible;
}
.el-table th>.cell {
  font-weight: bold;
  color: #000;
}
</style>
